package com.niit.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 用户登录的过滤器
 * @author Administrator
 *
 */
public class LoginFilter implements Filter{

	// 不需要过滤检查的url路径
	private String uncheckedUrls;
	private String[] unCheckedUrlArray;
	
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 获取web.xml所配置的不需要过滤处理的请求
		ServletContext servletContext = filterConfig.getServletContext();
		 uncheckedUrls = servletContext.getInitParameter("uncheckedUrls");
		 unCheckedUrlArray = uncheckedUrls.split(";");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 从request中获取请求路径
		HttpServletRequest req = (HttpServletRequest) request;
		String path = req.getServletPath();
		System.out.println("请求路径:"+path);
		// 设置过滤标识
		boolean flag= false;
		for(String str:unCheckedUrlArray) {
			if(path.contains(str)) {
				flag = true;
				break;
			}
		}
		if(flag) {// 不需要过滤检查的路径，直接放行请求
			System.out.println("放行");
			chain.doFilter(request, response);
		}else {
			// 需要过滤检查的路径，先判断是否已经登录
			HttpSession session = req.getSession();
			String username = (String) session.getAttribute("username");
			System.out.println("判断session,username = "+username);
			if(username == null || "".equals(username)) {// 用户名为空，表示未登录，重定向到登录页面
				HttpServletResponse res = (HttpServletResponse) response;
				res.sendRedirect("index.jsp");
			}else {// 用户名不为空，表示已经登录，放行该请求
				chain.doFilter(request, response);
			}
		}
	}

	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}
	

}
